<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\BaseController;
use app\middleware\api\Auth;
use app\model\SpecsValue;
use app\validate\api\CheckId;
use app\model\Carts as CartsModel;
class Carts extends BaseController
{
    protected $middleware=[Auth::class];

    /**
     * 购物车列表
     * @param int $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index($limit=10)
    {

        $data = CartsModel::where('users_id', request()->userid)
            ->with(['product', 'spec'])
            ->paginate($limit, false)
            ->each(function ($item) {
                if (!empty($item['spec'])) {
                    // 获取 specs_value_id，并拆分为数组
                    $specsValueIds = explode('_', $item['spec']['specs_value_id']);

                    // 查询 specs_value 表中的 name 字段
                    $specNames = SpecsValue::whereIn('id', $specsValueIds)->column('name');

                    // 将查询的名称数据赋给 sku
                    $item['spec']['sku'] = $specNames;
                }
            });

        return $this->success($data);

      return $this->success($data);
    }

    /**
     * 添加购物车
     * @return \think\response\Json
     * @throws \app\lib\exception\BaseException
     */
    public function add()
    {
        (new \app\validate\api\Carts())->goCheck();
        //加一个判断 同一个商品并且是同一个用户  修改数量
       $data= request()->param();
       $data['users_id']=request()->userid;
        CartsModel::create( $data);
        return $this->success();
    }

    /**
     * 修改购物车
     * @return \think\response\Json
     * @throws \app\lib\exception\BaseException
     */
    public function edit()
    {
        (new CheckId())->goCheck();
        $params=request()->param();
        CartsModel::where('id',$params['id'])->update($params);
        return $this->success();
    }

    /**
     * 删除购物车
     * @return \think\response\Json
     * @throws \app\lib\exception\BaseException
     */
    public function delete()
    {
        (new CheckId())->goCheck();
        $params=request()->param();
        CartsModel::where('id',$params['id'])->delete();
        return $this->success();
    }
}
